package com.gmp.product.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gmp.common.utils.DateUtils;
import com.gmp.product.service.IProductionOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.gmp.common.annotation.Log;
import com.gmp.common.core.controller.BaseController;
import com.gmp.common.core.domain.AjaxResult;
import com.gmp.common.enums.BusinessType;
import com.gmp.product.domain.WorkDispatch;
import com.gmp.product.service.IWorkDispatchService;
import com.gmp.common.utils.poi.ExcelUtil;
import com.gmp.common.core.page.TableDataInfo;

/**
 * 派单Controller
 * 
 * @author Koi
 * @date 2025-10-10
 */
@RestController
@RequestMapping("/product/dispatch")
@Api(tags = "派单管理")
public class WorkDispatchController extends BaseController
{
    @Autowired
    private IWorkDispatchService workDispatchService;

    @Autowired
    private IProductionOrderService productionOrderService;

    /**
     * 查询派单列表
     */
    @PreAuthorize("@ss.hasPermi('product:dispatch:list')")
    @GetMapping("/list")
    public TableDataInfo list(WorkDispatch workDispatch)
    {
        startPage();
        List<WorkDispatch> list = workDispatchService.selectWorkDispatchList(workDispatch);
        return getDataTable(list);
    }

    /**
     * 导出派单列表
     */
    @PreAuthorize("@ss.hasPermi('product:dispatch:export')")
    @Log(title = "派单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WorkDispatch workDispatch)
    {
        List<WorkDispatch> list = workDispatchService.selectWorkDispatchList(workDispatch);
        ExcelUtil<WorkDispatch> util = new ExcelUtil<WorkDispatch>(WorkDispatch.class);
        util.exportExcel(response, list, "派单数据");
    }

    /**
     * 获取派单详细信息
     */
    @PreAuthorize("@ss.hasPermi('product:dispatch:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(workDispatchService.selectWorkDispatchById(id));
    }

    /**
     * 新增派单
     */
    @PreAuthorize("@ss.hasPermi('product:dispatch:add')")
    @Log(title = "派单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WorkDispatch workDispatch)
    {
        // 时间戳前8位 + 4位随机数 = 12位ID（数字为主，重复概率较低）
        String timePart = String.valueOf(System.currentTimeMillis()).substring(0, 8);
        String randomPart = String.format("%04d", new Random().nextInt(10000));
        workDispatch.setWorkOrderCode(timePart + randomPart);
        workDispatch.setIsDelete(0);

        //设置派单时间
        workDispatch.setDispatchTime(DateUtils.getNowDate());
        workDispatch.setDispatchStatus(1L);//设置成待接单
        //设置派单人就让前端 直接传nickname 就行了
        //设置接收人 让求前端 直接传nickname 和userId 就行了

        //设置指令派工状态
        productionOrderService.updateDispatchStatus(workDispatch.getOrderCode(),1L);
        return toAjax(workDispatchService.save(workDispatch));
    }

    /**
     * 修改派单
     */
    @PreAuthorize("@ss.hasPermi('product:dispatch:edit')")
    @Log(title = "派单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WorkDispatch workDispatch)
    {
        workDispatch.setDispatchTime(DateUtils.getNowDate());
        //修改完派单之后 要让他 指令工单那里同时更新
        productionOrderService.updateDispatchStatus(workDispatch.getOrderCode(), workDispatch.getDispatchStatus());
        return toAjax(workDispatchService.updateWorkDispatch(workDispatch));
    }

    /**
     * 删除派单
     */
    @PreAuthorize("@ss.hasPermi('product:dispatch:remove')")
    @Log(title = "派单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(workDispatchService.removeBatchByIds(Arrays.asList(ids)));
    }

    //根据指令ID查询派单
    @GetMapping("/selectByOrderCode/{orderCode}")
    @PreAuthorize("@ss.hasPermi('product:dispatch:selectByOrderCode')")
    @ApiOperation("根据指令ID查询派单")
    public AjaxResult selectByOrderCode(@PathVariable String orderCode)
    {
        if(orderCode == null)
        {
            return error("指令ID不能为空");
        }
        LambdaQueryWrapper<WorkDispatch> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkDispatch::getOrderCode, orderCode);
        queryWrapper.eq(WorkDispatch::getIsDelete, 0);
        return success(workDispatchService.getOne(queryWrapper));
    }


}
